<template>
    <ul class="hanghang-list">
        <block v-for="(item, index) in news" :key="index">
            <view class="news-item" :data-id="item.id" @tap="toBookDetail">
                <li class="hanghang-list-first">
                    <div class="hanghang-list-name">
                        {{ item.title }}
                    </div>
                    <div class="hanghang-list-num">
                        {{ item.grade }}
                    </div>
                    <div class="hanghang-list-zuozhe">
                        {{ item.author }}
                    </div>
                    <div class="clearFloat">
                    </div>
                </li>
            </view>
        </block>


        <!-- 分页控件增强版 -->
        <view class="custom-pagination">
          <view class="page-info">
            第 {{ page.currentPage }}/{{ page.pages }} 页（共 {{ page.total }} 条）
          </view>
          
          <view class="page-jumper">
            <text>跳转</text>
            <input 
              v-model.number="jumpPage" 
              type="number" 
              class="page-input"
              :min="1"
              :max="page.pages"
            />
            <button @click="handleJump" size="mini" class="btn-page-go">GO</button>

            <!-- <button 
              class="page-btn prev-btn" 
              :disabled="page.currentPage <= 1"
              @click="handlePrevPage"
            >
              上一页
            </button>
            <button 
              class="page-btn next-btn" 
              :disabled="page.currentPage >= page.pages"
              @click="handleNextPage"
            >
              下一页
            </button> -->
          </view>
        </view>
    </ul>
</template>
<script setup>
    import { ref,inject,watch } from 'vue'
    import { useRouter } from 'vue-router';
    import navBar from '@/pages/components/nav-bar.vue';
    import commonList from '@/pages/index/common-list.vue';
    import { useStore } from 'vuex'; // 引入 Vuex

    const store = useStore(); // 获取 Vuex Store

    const router = useRouter();

    // 从父组件注入共享状态
    const activeId = inject('activeId')
    const categoryId = inject('categoryId')
    const page = inject('page')
    // const getDataList = inject('getDataList')

    const currentIndex = ref(0)

    const bookList = [
      { image: '/static/images/book/5cda53f056b56.jpg' },
      { image: '/static/images/book/5cda53fdc864b.jpg' }
    ]

    const onSwiperChange = (e) => {
      currentIndex.value = e.detail.current
    }

    const swipePrev = () => {
      const newIndex = currentIndex.value - 1
      currentIndex.value = newIndex < 0 ? bookList.length - 1 : newIndex
    }

    const swipeNext = () => {
      const newIndex = currentIndex.value + 1
      currentIndex.value = newIndex >= bookList.length ? 0 : newIndex
    }

    const news = ref([])

    const getDataList = (pageParam, params, done) => {
      dataListLoading.value = true

      const queryParams = {
          current: pageParam?.currentPage || page.currentPage,
          size: pageParam?.pageSize || page.pageSize,
          ...params
      };

        let addiUrl = '';
        if (categoryId.value) {
          queryParams.categoryId = categoryId.value;
          // addiUrl = `&categoryId=${categoryId.value}`;
        }

        if(store.state.keyword){
            queryParams.keyword = store.state.keyword;
        }

        // 更新浏览器 URL（不触发页面刷新）
        router.push({
          query: queryParams // 同步参数到 URL，如 ?current=1&size=20
        });

      http.request({
        // url: '/shop/book/bookList?current=' + page.currentPage,
        url: `/shop/book/bookList`,
        method: 'GET',
        data: queryParams
      })
      .then(({ data }) => {
        dataList.value = data.records
        page.total = data.total
        page.pages = data.pages
        dataListLoading.value = false
        news.value = data.records
        done?.()
      })
      .catch(() => {
        dataListLoading.value = false
        done?.()
      })
    }

    /**
     * 生命周期函数--监听页面显示
     */
    onShow(() => {
        // getDataList();
        // listCategoryBook();
    });

    const jumpPage = ref('')
    const handleJump = () => {
      if (jumpPage.value >= 1 && jumpPage.value <= page.pages) {
        page.currentPage = Number(jumpPage.value)
        getDataList();
      }else{
        handleNextPage();
      }
      jumpPage.value = ''
    }
        
    const dataList = ref([])
    // const page = reactive({
    //   total: 0, // 总页数
    //   currentPage: 1, // 当前页数
    //   pageSize: 20, // 每页显示多少条
    //   pages: 0 // 总页数
    // })
    const dataListLoading = ref(false)
    const addOrUpdateVisible = ref(false)

    // let activeId = ref(0);
    // const categoryId = ref(0);
    onLoad((options) => {
        page.currentPage = options?.current || 1;
        activeId.value = Number(options?.categoryId) || 0;
        categoryId.value = Number(options?.categoryId) || 0;

        console.log('results_test_onlyback:', options);
        getDataList();
    });

    onHide(() => {
        activeId.value = 0;
        categoryId.value = 0;
    });

    const handlePrevPage = () => {
      if (page.currentPage > 1) {
        page.currentPage--
        getDataList()
      }
    }

    const handleNextPage = () => {
      if (page.currentPage < page.pages) {
        page.currentPage++
        getDataList()
      }
    }

    const toBookDetail = (e) => {

      let pageStr = '';
      if(page.currentPage>1){
        pageStr = `&current=${page.currentPage}`;
      }

      let addiUrl = '';
      addiUrl = `&isCategory=1`;
      if (categoryId.value) {
        addiUrl += `&categoryId=${categoryId.value}`;
        // addiUrl = `&categoryId=${categoryId.value}`;
      }
      
      uni.navigateTo({
        // url: '/pages/index/book-detail?id=' + e.currentTarget.dataset.id
        url: `/pages/index/book-detail?id=${e.currentTarget.dataset.id}${pageStr}${addiUrl}`
      })
    }

    // 监听 Vuex 中的 keyword 状态变化
    watch(
      () => store.state.keyword,
      (newIsSearch) => {
        // if (newIsSearch) {
          // 调用子组件加载数据，传递搜索关键词
          getDataList({
            keyword: store.state.keyword
          });
        // }
      }
    );

    // 暴露函数给父组件调用
    defineExpose({ getDataList });

</script>

<style scoped lang="scss">
    @use './index.scss'; 

    /* 分页 start */
    .pagination-container {
      padding: 20rpx;
    }

    .data-item {
      padding: 24rpx;
      border-bottom: 1rpx solid #eee;
    }

    .custom-pagination {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 30rpx;
      padding: 20rpx 0;
      /*border-top: 1rpx solid #f0f0f0;*/
    }

    .page-info {
      margin-bottom: 15rpx;
      font-size: 26rpx;
      color: #000;
    }

    .page-jumper {
      display: flex;
      align-items: center;
      margin-top: 15rpx;
    }

    .page-input {
      width: 80rpx;
      height: 50rpx;
      margin: 0 10rpx;
      border: 1rpx solid #ddd;
      text-align: center;
      border-radius: 6rpx;
      background:#fff;
    }
    .btn-page-go {
        padding: 3px 20px;
    }

    .pagination-buttons {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 15rpx 0;
      gap: 20rpx;
    }

    .page-btn {
      padding: 8rpx 20rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      background-color: #f8f8f8;
      border: 1rpx solid #ddd;
      
      &[disabled] {
        opacity: 0.5;
        cursor: not-allowed;
      }
      
      &.prev-btn {
        margin-right: 20rpx;
      }
      
      &.next-btn {
        margin-left: 20rpx;
      }
    }
    /* 分页 end */
</style>